package com.hc.likelistenmusic.fragment

import android.Manifest
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.provider.MediaStore
import android.text.InputType
import android.text.TextUtils
import android.text.method.TextKeyListener
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.animation.AnimationUtils
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.TextView.OnEditorActionListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.hc.likelistenmusic.R
import com.hc.likelistenmusic.activity.LocalMusicActivity
import com.hc.likelistenmusic.adapter.LocalMusicAdapter
import com.hc.likelistenmusic.adapter.LocalMusicFilterAdapter
import com.hc.likelistenmusic.bean.LocalMusic
import com.hc.likelistenmusic.util.LrcUtil
import com.hc.likelistenmusic.util.ScreenUtil
import com.hc.likelistenmusic.util.XPermissionUtil
import com.hc.likelistenmusic.view.RoundRotateProgressView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Collections
import kotlin.random.Random

class LocalMusicFragment : LazyFragment(false) {
    val TAG = "HUACHEN_MusicFragment"
    lateinit var mIv_fm_center: ImageView
    lateinit var mIv_fm_back: ImageView
    lateinit var mIv_fm_playmode: ImageView
    lateinit var mIv_fm_location: ImageView
    lateinit var mIv_fm_filter: ImageView
    lateinit var mIv_fm_filter_cancel: ImageView
    lateinit var mTv_fm_rescan_local: TextView
    lateinit var mEt_fm_filter_musics: EditText
    lateinit var mRv_fm_local_musics: RecyclerView
    lateinit var mRv_fm_filter: RecyclerView
    lateinit var mRrpv_fm: RoundRotateProgressView
    lateinit var mTv_fm_musicInfo: TextView
    lateinit var mTv_fm_musicDuration: TextView
    lateinit var mTv_fm_srolled_bottom: TextView
    lateinit var mTv_fm_srolled_top: TextView
    lateinit var mIv_fm_play: ImageView
    lateinit var mLocalMusicAdapter: LocalMusicAdapter
    lateinit var mLocalMusicFilterAdapter: LocalMusicFilterAdapter
    lateinit var mLocalMusicActivity: LocalMusicActivity
    var mLocalMusicList = mutableListOf<LocalMusic>()
    var mLocalMusicFilterList = mutableListOf<LocalMusic>()
    var mLoadLocalMusicJob: Job? = null
    val mUnknownAlbumKey = "unknown"
    val mUnknownAlbumValue = "未知专辑"
    var mCurrentItemSelectedPosition = -1
    var mIsHandControl = false
    var mMode = 1
    override fun initView(rootView: View) {
        mLocalMusicActivity = activity as LocalMusicActivity
        mIv_fm_center = rootView.findViewById(R.id.iv_fm_center)
        mIv_fm_back = rootView.findViewById(R.id.iv_fm_back)
        mIv_fm_playmode = rootView.findViewById(R.id.iv_fm_playmode)
        mIv_fm_location = rootView.findViewById(R.id.iv_fm_location)
        mIv_fm_filter = rootView.findViewById(R.id.iv_fm_filter)
        mIv_fm_filter_cancel = rootView.findViewById(R.id.iv_fm_filter_cancel)
        mEt_fm_filter_musics = rootView.findViewById(R.id.et_fm_filter_musics)
        mTv_fm_rescan_local = rootView.findViewById(R.id.tv_fm_rescan_local)
        mRv_fm_local_musics = rootView.findViewById(R.id.rv_fm_local_musics)
        mRv_fm_filter = rootView.findViewById(R.id.rv_fm_filter)
        mRrpv_fm = rootView.findViewById(R.id.rrpv_fm)
        mRrpv_fm.setBimap(BitmapFactory.decodeResource(resources, R.drawable.app_logo))
        mTv_fm_musicInfo = rootView.findViewById(R.id.tv_fm_musicInfo)
        mTv_fm_musicInfo.isSelected = true
        mTv_fm_musicDuration = rootView.findViewById(R.id.tv_fm_musicDuration)
        mTv_fm_srolled_bottom = rootView.findViewById(R.id.tv_fm_srolled_bottom)
        mTv_fm_srolled_top = rootView.findViewById(R.id.tv_fm_srolled_top)
        mIv_fm_play = rootView.findViewById(R.id.iv_fm_play)
        mRv_fm_local_musics.apply {
            layoutManager = LinearLayoutManager(context)
            mLocalMusicAdapter =
                LocalMusicAdapter(context, R.layout.fragment_music_rv_item, mLocalMusicList)
            mLocalMusicAdapter.setOnItemClickListener { lm, p ->
                onItemClick(lm, p)
            }
            adapter = mLocalMusicAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        showOrHideLocation(false)
                    } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                        showOrHideLocation(true)
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (dy > 0 && !recyclerView.canScrollVertically(1)) {
                        showOrHideTopAndBottom(false)
                    } else if (dy < 0 && !recyclerView.canScrollVertically(-1)) {
                        showOrHideTopAndBottom(true)
                    }
                }
            })
        }
        mRv_fm_filter.apply {
            layoutManager = LinearLayoutManager(context)
            mLocalMusicFilterAdapter = LocalMusicFilterAdapter(
                context,
                R.layout.fragment_music_rv_filter_item,
                mLocalMusicFilterList
            )
            mLocalMusicFilterAdapter.setOnItemClickListener { lm, p ->
                onFilterItemClick(lm)
            }
            adapter = mLocalMusicFilterAdapter
            addOnScrollListener(object : OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (dy > 0 && !recyclerView.canScrollVertically(1)) {
                        showOrHideTopAndBottom(false)
                    } else if (dy < 0 && !recyclerView.canScrollVertically(-1)) {
                        showOrHideTopAndBottom(true)
                    }
                }
            })
        }
        mTv_fm_rescan_local.setOnClickListener {
            loadLocalMusics(mLocalMusicActivity)
        }
        mIv_fm_play.setOnClickListener {
            onPlayOrPauseClick()
        }
        mIv_fm_back.setOnClickListener {
            mLocalMusicActivity.showExitDialog()
        }
        mIv_fm_playmode.setOnClickListener {
            onPlayModeClick()
        }
        mIv_fm_location.setOnClickListener {
            onLocationClick()
        }
        mIv_fm_filter_cancel.setOnClickListener {
            onFilterOrCancelClick(true)
        }
        mIv_fm_filter.setOnClickListener {
            onFilterOrCancelClick(false)
        }
        mEt_fm_filter_musics.keyListener = object : TextKeyListener(Capitalize.NONE, false) {
            override fun getInputType(): Int {
                return InputType.TYPE_MASK_CLASS
            }
        }
        mEt_fm_filter_musics.setOnEditorActionListener(object : OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onFilterOrCancelClick(false)
                    return true
                }
                return false
            }
        })
    }

    private fun showOrHideTopAndBottom(top: Boolean) {
        if (top) {
            mTv_fm_srolled_top.visibility = VISIBLE
            CoroutineScope(Dispatchers.IO).launch {
                delay(1000)
                CoroutineScope(Dispatchers.Main).launch {
                    mTv_fm_srolled_top.visibility = INVISIBLE
                }
            }
        } else {
            mTv_fm_srolled_bottom.visibility = VISIBLE
            CoroutineScope(Dispatchers.IO).launch {
                delay(1000)
                CoroutineScope(Dispatchers.Main).launch {
                    mTv_fm_srolled_bottom.visibility = INVISIBLE
                }
            }
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.fragment_music
    }

    override fun startLazyLoad() {
        super.startLazyLoad()
        loadLocalMusics(mLocalMusicActivity)
    }

    fun onFilterItemClick(lm: LocalMusic) {
        (0..mLocalMusicList.size).forEach {
            if (mLocalMusicList[it].path == lm.path) {
                if (mCurrentItemSelectedPosition == -1) {
                    mCurrentItemSelectedPosition = it
                    mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 2
                    mLocalMusicAdapter.notifyItemChanged(mCurrentItemSelectedPosition)
                    onLocationClick()
                    startPrepareMusicInner(lm)
                } else {
                    if (mCurrentItemSelectedPosition == it) {
                        onSearchOrNotificationClick(true)
                    } else {
                        mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 1
                        mLocalMusicAdapter.notifyItemChanged(mCurrentItemSelectedPosition)
                        mCurrentItemSelectedPosition = it
                        mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 2
                        mLocalMusicAdapter.notifyItemChanged(mCurrentItemSelectedPosition)
                        onLocationClick()
                        startPrepareMusicInner(lm)
                    }
                }
                hideFilterList()
                return
            }
        }
    }

    private fun hideFilterList(){
        mLocalMusicFilterList.clear()
        mLocalMusicFilterAdapter.notifyDataSetChanged()
        mRv_fm_filter.visibility = GONE
        mRv_fm_local_musics.visibility = VISIBLE
        mIv_fm_playmode.visibility = VISIBLE
        mIv_fm_location.visibility = VISIBLE
        mEt_fm_filter_musics.setText("")
        mEt_fm_filter_musics.clearFocus()
    }

    fun onFilterOrCancelClick(cancel: Boolean) {
        ScreenUtil.hideSoftInput(mLocalMusicActivity, mEt_fm_filter_musics)
        mEt_fm_filter_musics.clearFocus()
        mLocalMusicFilterList.clear()
        if (cancel) {
            mRv_fm_filter.visibility = GONE
            mRv_fm_local_musics.visibility = VISIBLE
            mIv_fm_location.visibility = VISIBLE
            mIv_fm_playmode.visibility = VISIBLE
            mEt_fm_filter_musics.setText("")
        } else {
            val filter_text = mEt_fm_filter_musics.text
            if (TextUtils.isEmpty(filter_text)) {
                mEt_fm_filter_musics.startAnimation(
                    AnimationUtils.loadAnimation(
                        mLocalMusicActivity,
                        R.anim.shake
                    )
                )
                return
            }
            mIv_fm_location.visibility = GONE
            mIv_fm_playmode.visibility = GONE
            mLocalMusicList.forEach {
                if (it.name.contains(filter_text) || it.singer.contains(filter_text)) {
                    mLocalMusicFilterList.add(it)
                }
            }
            if (mLocalMusicFilterList.isEmpty()) {
                mLocalMusicActivity.showFilterFailToast()
                mRv_fm_local_musics.visibility = VISIBLE
                mRv_fm_filter.visibility = GONE
                mEt_fm_filter_musics.setText("")
            } else {
                sortLocalMusicsBySingerAndName(mLocalMusicFilterList)
                if(mCurrentItemSelectedPosition != -1){
                    var index:Int = -1
                    mLocalMusicFilterList.forEachIndexed { i, item ->
                        if(item.path == mLocalMusicList[mCurrentItemSelectedPosition].path){
                            index = i
                        }
                    }
                    if(index != -1){
                        val localMusic = mLocalMusicFilterList.removeAt(index)
                        mLocalMusicFilterList.add(0,localMusic)
                    }
                }
                mRv_fm_local_musics.visibility = GONE
                mRv_fm_filter.visibility = VISIBLE
            }
        }
        mLocalMusicFilterAdapter.notifyDataSetChanged()

    }

    fun showOrHideLocation(isScorll: Boolean) {
        if (mCurrentItemSelectedPosition != -1) {
            if (isScorll) {
                mIv_fm_location.visibility = GONE
            } else {
                CoroutineScope(Dispatchers.Main).launch {
                    delay(1000)
                    mIv_fm_location.visibility = VISIBLE
                }
            }
        }
    }

    fun onLocationClick() {
        (mRv_fm_local_musics.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
            mCurrentItemSelectedPosition,
            0
        )
    }

    fun onPlayModeClick() {
        when (mMode) {
            1 -> {
                mMode = 2
                mIv_fm_playmode.setImageResource(R.drawable.img_mode_single_repeat)
            }

            2 -> {
                mMode = 3
                mIv_fm_playmode.setImageResource(R.drawable.img_mode_random_repeat)
            }

            else -> {
                mMode = 1
                mIv_fm_playmode.setImageResource(R.drawable.img_mode_list_repeat)
            }
        }
        mLocalMusicActivity.onPlayModeChangedFromMf(mMode)
    }

    fun onPlayOrPauseClick() {
        if (mCurrentItemSelectedPosition != -1 && !mLocalMusicFilterList.isEmpty()) {
            (0..<mLocalMusicFilterList.size).forEach {
                if (mLocalMusicFilterList[it].path == mLocalMusicList[mCurrentItemSelectedPosition].path) {
                    mLocalMusicFilterList[it].selectedType =
                        mLocalMusicList[mCurrentItemSelectedPosition].selectedType
                    mLocalMusicFilterAdapter.notifyItemChanged(it)
                }
            }
        }
        if (mCurrentItemSelectedPosition == -1) {
            mIsHandControl = true
            mCurrentItemSelectedPosition = 0
            mLocalMusicList[0].selectedType = 2
            mLocalMusicAdapter.notifyItemChanged(0)
            startPrepareMusicInner(mLocalMusicList[0])
        } else {
            onMeidaPlayOrPause()
        }
    }

    fun onItemClick(lm: LocalMusic, p: Int) {
        when (mCurrentItemSelectedPosition == -1) {
            true -> {
                mCurrentItemSelectedPosition = p
                onItemClickUI(p, mCurrentItemSelectedPosition, lm)
            }

            else -> {
                if (mCurrentItemSelectedPosition != p) {
                    onItemClickUI(mCurrentItemSelectedPosition, p, lm)
                    mCurrentItemSelectedPosition = p
                } else {
                    onMeidaPlayOrPause()
                }
            }
        }
    }

    fun onSearchOrNotificationClick(search: Boolean) {
        val isPlaying = mLocalMusicActivity.isPlaying()
        if (search) {
            if (!isPlaying) {
                mIsHandControl = false
                mLocalMusicActivity.play()
                mRrpv_fm.startAnim()
                mTv_fm_musicInfo.isSelected = true
                mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 2
                mIv_fm_play.setImageResource(R.drawable.img_pause)
                mLocalMusicActivity.sendProgress()
                mLocalMusicActivity.changeLfStartOrPause(true)
                mLocalMusicActivity.updateNotification(true)
            }
        } else {
            if (isPlaying) {
                mIsHandControl = true
                mLocalMusicActivity.pause()
                mRrpv_fm.pauseAnim()
                mTv_fm_musicInfo.isSelected = false
                mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 3
                mIv_fm_play.setImageResource(R.drawable.img_play)
                mLocalMusicActivity.cancelProgress()
                mLocalMusicActivity.changeLfStartOrPause(false)
                mLocalMusicActivity.updateNotification(false)
            }
        }
        mLocalMusicAdapter.notifyItemChanged(mCurrentItemSelectedPosition)
    }

    fun onMeidaPlayOrPause() {
        val playing = mLocalMusicActivity.isPlaying()
        if (playing) {
            mIsHandControl = true
            mLocalMusicActivity.pause()
            mRrpv_fm.pauseAnim()
            mTv_fm_musicInfo.isSelected = false
            mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 3
            mIv_fm_play.setImageResource(R.drawable.img_play)
            mLocalMusicActivity.cancelProgress()
            mLocalMusicActivity.changeLfStartOrPause(false)
            mLocalMusicActivity.updateNotification(false)
        } else {
            mIsHandControl = false
            mLocalMusicActivity.play()
            mRrpv_fm.startAnim()
            mTv_fm_musicInfo.isSelected = true
            mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 2
            mIv_fm_play.setImageResource(R.drawable.img_pause)
            mLocalMusicActivity.sendProgress()
            mLocalMusicActivity.changeLfStartOrPause(true)
            mLocalMusicActivity.updateNotification(true)
        }

        mLocalMusicAdapter.notifyItemChanged(mCurrentItemSelectedPosition)
    }

    fun resumeOrPauseRotate(pause: Boolean) {
        if (pause) {
            mRrpv_fm.pauseAnim()
            mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 3
            mIv_fm_play.setImageResource(R.drawable.img_play)
        } else {
            mRrpv_fm.startAnim()
            mLocalMusicList[mCurrentItemSelectedPosition].selectedType = 2
            mIv_fm_play.setImageResource(R.drawable.img_pause)
        }
        mLocalMusicAdapter.notifyItemChanged(mCurrentItemSelectedPosition)
    }

    fun onItemClickUI(prep: Int?, currentp: Int, lm: LocalMusic) {
        mIsHandControl = false
        mCurrentItemSelectedPosition = currentp
        mIv_fm_play.setImageResource(R.drawable.img_play)
        mTv_fm_musicDuration.text = "${LrcUtil.formatLrcTime(0)}/${LrcUtil.formatLrcTime(0)}"
        hideFilterList()
        mLocalMusicList.apply {
            prep?.let {
                this[it].selectedType = 1
                mLocalMusicAdapter.notifyItemChanged(it)
            }
            this[currentp].selectedType = 2
        }
        mLocalMusicAdapter.notifyItemChanged(currentp)
        startPrepareMusicInner(lm)
    }

    fun startPrepareMusicInner(lm: LocalMusic) {
        Log.d(TAG, "开始缓冲歌曲:${lm.path}")
        mLocalMusicActivity.startPrepareMusic(lm)
    }

    fun autoSyncMusicProgress(currentProgress: Int, duration: Int) {
        mRrpv_fm.setProgress(currentProgress, duration)
        mTv_fm_musicDuration.text =
            "${LrcUtil.formatLrcTime(currentProgress)}/${LrcUtil.formatLrcTime(duration)}"
    }

    fun onMediaPlayerPrepared() {
        mRrpv_fm.startAnim()
        mIv_fm_play.setImageResource(R.drawable.img_pause)
        val localMusic = mLocalMusicList[mCurrentItemSelectedPosition]
        mTv_fm_musicInfo.text = "${localMusic.name} - ${localMusic.singer}"
        mTv_fm_musicInfo.isSelected = true
    }

    fun autoChangeNextSong() {
        mRrpv_fm.resetProgress()
        val size = mLocalMusicList.size
        if (size == 0) {
            return
        }
        val prep = mCurrentItemSelectedPosition
        when (mMode) {
            1 -> {
                var next = mCurrentItemSelectedPosition + 1
                if (next == size) {
                    next = 0
                }
                mCurrentItemSelectedPosition = next
            }

            2 -> {
                mCurrentItemSelectedPosition = prep
            }

            else -> {
                if (size == 1) {
                    mCurrentItemSelectedPosition = prep
                } else {
                    while (true) {
                        var n = Random.nextInt(size)
                        if (prep != n) {
                            mCurrentItemSelectedPosition = n
                            break
                        }
                    }
                }
            }
        }
        onItemClickUI(
            prep,
            mCurrentItemSelectedPosition,
            mLocalMusicList[mCurrentItemSelectedPosition]
        )
    }

    fun handChangeNextSong(next: Boolean) {
        val size = mLocalMusicList.size
        if (size == 0) {
            mLocalMusicActivity.showNoMusicFromLrcToast()
            return
        }
        var currentP: Int = mCurrentItemSelectedPosition
        when (mMode) {
            1 -> {
                if (next) {
                    var nextP: Int
                    if (currentP == -1) {
                        nextP = 0
                        mCurrentItemSelectedPosition = nextP
                        onItemClickUI(
                            null,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    } else {
                        nextP = currentP + 1
                        if (nextP == size) {
                            nextP = 0
                        }
                        mCurrentItemSelectedPosition = nextP
                        onItemClickUI(
                            currentP,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    }
                } else {
                    var nextP: Int
                    if (currentP == -1) {
                        nextP = size - 1
                        mCurrentItemSelectedPosition = nextP
                        onItemClickUI(
                            null,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    } else {
                        nextP = currentP - 1
                        if (nextP == -1) {
                            nextP = size - 1
                        }
                        mCurrentItemSelectedPosition = nextP
                        onItemClickUI(
                            currentP,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    }
                }
            }

            2 -> {
                if (next) {
                    if (currentP == -1) {
                        mCurrentItemSelectedPosition = 0
                        onItemClickUI(
                            null,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    } else {
                        mCurrentItemSelectedPosition = currentP
                        onItemClickUI(
                            currentP,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    }
                } else {
                    if (currentP == -1) {
                        mCurrentItemSelectedPosition = size - 1
                        onItemClickUI(
                            null,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    } else {
                        mCurrentItemSelectedPosition = currentP
                        onItemClickUI(
                            currentP,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    }
                }
            }

            else -> {
                if (currentP == -1) {
                    mCurrentItemSelectedPosition = Random.nextInt(size)
                    onItemClickUI(
                        null,
                        mCurrentItemSelectedPosition,
                        mLocalMusicList[mCurrentItemSelectedPosition]
                    )
                } else {
                    if (size == 1) {
                        mCurrentItemSelectedPosition = currentP
                        onItemClickUI(
                            currentP,
                            mCurrentItemSelectedPosition,
                            mLocalMusicList[mCurrentItemSelectedPosition]
                        )
                    } else {
                        while (true) {
                            var n = Random.nextInt(size)
                            if (currentP != n) {
                                mCurrentItemSelectedPosition = n
                                onItemClickUI(
                                    currentP,
                                    mCurrentItemSelectedPosition,
                                    mLocalMusicList[mCurrentItemSelectedPosition]
                                )
                                break
                            }
                        }
                    }
                }
            }
        }
        onLocationClick()
    }

    fun refreshAlbumImg(hasAlbum: Boolean, bitmap: Bitmap?) {
        if(::mRrpv_fm.isInitialized){
            if (hasAlbum) {
                bitmap?.let { mRrpv_fm.setBimap(it) }
            } else {
                mRrpv_fm.setBimap(BitmapFactory.decodeResource(resources, R.drawable.app_logo))
            }
        }
    }

    fun reset() {
        mIv_fm_center.visibility = VISIBLE
        mTv_fm_rescan_local.visibility = VISIBLE
        mRv_fm_local_musics.visibility = GONE
        mRv_fm_filter.visibility = GONE
        mEt_fm_filter_musics.visibility = GONE
        mIv_fm_filter.visibility = GONE
        mIv_fm_filter_cancel.visibility = GONE
        mRrpv_fm.visibility = GONE
        mTv_fm_musicInfo.visibility = GONE
        mTv_fm_musicDuration.visibility = GONE
        mIv_fm_play.visibility = GONE
        mIv_fm_location.visibility = GONE
        mIv_fm_playmode.visibility = GONE
    }

    fun loadLocalMusics(context: Context?) {
        mLoadLocalMusicJob = CoroutineScope(Dispatchers.IO).launch {
            var localMusicList = loadLocalMusicsInner(context, object : ScanlingListener {
                override fun onScanling(size: Int) {
                    launch(Dispatchers.Main) {
                        mLocalMusicActivity.showScanlingDialogSize(size)
                    }
                }
            })
            mLocalMusicList.clear()
            mLocalMusicList.addAll(localMusicList)
            mLocalMusicList.let {
                withContext(Dispatchers.Main) {
                    mLocalMusicActivity.mScaningDialog.dismiss()
                    if (it.isNotEmpty()) {
                        mIv_fm_center.visibility = GONE
                        mTv_fm_rescan_local.visibility = GONE
                        mRv_fm_local_musics.visibility = VISIBLE
                        mRv_fm_filter.visibility = GONE
                        mEt_fm_filter_musics.visibility = VISIBLE
                        mIv_fm_filter.visibility = VISIBLE
                        mIv_fm_filter_cancel.visibility = VISIBLE
                        mRrpv_fm.visibility = VISIBLE
                        mTv_fm_musicInfo.visibility = VISIBLE
                        mTv_fm_musicDuration.visibility = VISIBLE
                        mIv_fm_play.visibility = VISIBLE
                        mIv_fm_location.visibility = VISIBLE
                        mIv_fm_playmode.visibility = VISIBLE
                    } else {
                        mIv_fm_center.visibility = VISIBLE
                        mTv_fm_rescan_local.visibility = VISIBLE
                        mRv_fm_local_musics.visibility = GONE
                        mRv_fm_filter.visibility = GONE
                        mEt_fm_filter_musics.visibility = GONE
                        mIv_fm_filter.visibility = GONE
                        mIv_fm_filter_cancel.visibility = GONE
                        mRrpv_fm.visibility = GONE
                        mTv_fm_musicInfo.visibility = GONE
                        mTv_fm_musicDuration.visibility = GONE
                        mIv_fm_play.visibility = GONE
                        mIv_fm_location.visibility = GONE
                        mIv_fm_playmode.visibility = GONE
                        if (XPermissionUtil.ensurePermission(
                                mLocalMusicActivity,
                                null,
                                generateExternalStoragePermission()
                            )
                        ) {
                            mLocalMusicActivity.showNoMusicFromMusicToast(true)
                        } else {
                            mLocalMusicActivity.showNoMusicFromMusicToast(false)
                            LazyLoadFail()
                        }
                    }
                    mLocalMusicAdapter.notifyDataSetChanged()
                    mLocalMusicActivity.dismissScanlingDialog()
                }
            }
        }
    }

    private suspend fun loadLocalMusicsInner(
        context: Context?,
        listener: ScanlingListener
    ): List<LocalMusic> {
        val cursor = context?.contentResolver?.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null, null, null, MediaStore.Audio.Media.IS_MUSIC
        )
        var songLists = mutableListOf<LocalMusic>()
        cursor?.let {
            while (it.moveToNext()) {
                val path = it.getString(it.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
                val album = it.getString(it.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM))
                Log.d(TAG, "已扫描到歌曲:${path}")
                if (!path.contains("Music/LLM/LM") || !path.contains(".mp3") || !path.contains("__")) {
                    continue
                }
                Log.d(TAG, "添加歌曲:${path}")
                var name = path.substring(path.lastIndexOf("__") + 2, path.lastIndexOf(".mp3"))
                var singer = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("__"))
                var duration = it.getInt(it.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION))
                val size = it.getLong(it.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE))
                val year = it.getLong(it.getColumnIndexOrThrow(MediaStore.Audio.Media.YEAR))
                var syear = if(year==0L){"未知发行年份"}else{"${year}"}
                val fixalbum = if (album.contains(mUnknownAlbumKey) or ("LM" == album)) {
                    mUnknownAlbumValue
                } else {
                    album
                }
                val song = LocalMusic(path, singer, name, fixalbum, duration, size,syear)
                song.durationString = song.convertDuration()
                songLists.add(song)
                listener.onScanling(songLists.size)
            }
            sortLocalMusicsBySingerAndName(songLists)
            return songLists
        }
        return songLists
    }

    private fun sortLocalMusicsBySingerAndName(src:List<LocalMusic>){
        Collections.sort(src,object :Comparator<LocalMusic>{
            override fun compare(o1: LocalMusic, o2: LocalMusic): Int {
                return o1.name.compareTo(o2.name)
            }
        })
        Collections.sort(src,object :Comparator<LocalMusic>{
            override fun compare(o1: LocalMusic, o2: LocalMusic): Int {
                return o1.singer.compareTo(o2.singer)
            }
        })
    }

    fun generateExternalStoragePermission(): List<String> {
        return mutableListOf<String>().apply {
            if ((mLocalMusicActivity.applicationInfo.targetSdkVersion) >= Build.VERSION_CODES.TIRAMISU) {
                add(Manifest.permission.READ_MEDIA_IMAGES)
                add(Manifest.permission.READ_MEDIA_VIDEO)
                add(Manifest.permission.READ_MEDIA_AUDIO)
            } else {
                add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
    }

    fun onError() {
        if(::mRrpv_fm.isInitialized){
            mRrpv_fm.error()
        }
    }

    interface ScanlingListener {
        fun onScanling(size: Int)
    }
}